<?php

namespace App\Http\Controllers\Api;

use App\Models\User;
use App\Services\WechatService;
use Illuminate\Http\Request;
use EasyWeChat;
use DB;
use GuzzleHttp\Client;

class WechatController extends BaseController
{
    protected $wechatService;

    // 利用 Laravel 的自动解析功能注入 CartService 类
    public function __construct(WechatService $wechatService)
    {
        parent::__construct();
        $this->wechatService = $wechatService;
    }

    public function test()
    {

        $client = new Client();
        $access_token = $this->wechatService->getAccessToken();
        $url = 'https://api.weixin.qq.com/cgi-bin/express/business/delivery/getall';

        $query = array_filter([
            'access_token' => $access_token['access_token'],
        ]);

        $response = $client->get($url, [
            'query' => $query,
        ])->getBody()->getContents();



        dd(json_decode($response, true));
    }

    public function getSession(Request $request)
    {
        $code = trim($request->get('code'));

        if(empty($code))
        {
            return $this->err(1,200,'','参数错误');
        }

        $miniProgram = EasyWeChat::miniProgram(); // 小程序
        $result = $miniProgram->auth->session($code);
        if(isset($result['errcode']))
        {
            return $this->err(10000,200,'',$result['errmsg']);
        }


        $row = \DB::table('wechat_mini_session_key')->where('openid',$result['openid'])->first();
        if(!empty($row))
        {
            \DB::table('wechat_mini_session_key')->where('openid',$result['openid'])->update(['session_key'=>$result['session_key']]);
        }
        else
        {
            \DB::table('wechat_mini_session_key')->insert(['openid'=>$result['openid'],'session_key'=>$result['session_key']]);
        }
        return $this->res([
            'data' => [
                'openid'      => $result['openid'],
                //'session_key' => $result['session_key'],
                //'unionid'     => isset($result['unionid']) ? $result['unionid'] : '',
            ]
        ]);
    }

    public function register(Request $request)
    {
        $openid             = trim($request->get('openid'));
        $recommend_user_id  = intval($request->get('recommend_user_id'));

        if(empty($openid))
        {
            return $this->err(1,200,'','参数错误');
        }

        $user = User::where('wechat_openid',$openid)->first();

        $is_new_user = 0;
        $data = [];
        if(empty($user))
        {
            if(!empty($recommend_user_id))
            {
                $is_new_user = 1;
                $data['recommend_user_id'] = $recommend_user_id;
            }

            $data['wechat_openid'] = $openid;
            $data['user_type'] = 1;
            $data['created_at'] = $this->time;
            $data['updated_at'] = $this->time;

            $user = User::create($data);
        }

        $result = [
            'user_id'     => $user->id,
            'is_new_user' => $is_new_user,
        ];
        return $this->ok($result);
    }

    public function store(Request $request)
    {
        $openid            = trim($request->get('openid'));
        $nickName          = trim($request->get('nickName'));
        $avatarUrl         = trim($request->get('avatarUrl'));
        $encryptedData     = $request->get('encryptedData');
        $iv                = $request->get('iv');
        $recommend_user_id = intval($request->get('recommend_user_id'));


        if(empty($openid) || empty($nickName))
        {
            return $this->err(1,200,'','参数错误');
        }

        $session_key_row = DB::table('wechat_mini_session_key')->where('openid',$openid)->first();

        if(empty($avatarUrl))
        {
            $avatarUrl = '';
        }

        $data = [
            'wechat_avatar'   => $avatarUrl,
            'wechat_nickname' => $nickName,
            'wechat_openid'   => $openid,
        ];
        $user = User::where('wechat_openid',$openid)->first();
        $is_new_user = 0;
        if(empty($user))
        {
            if(!empty($recommend_user_id))
            {
                $is_new_user = 1;
                $data['recommend_user_id'] = $recommend_user_id;
            }
            $data['user_type'] = 1;
            $data['created_at'] = $this->time;
            $data['updated_at'] = $this->time;

            $user = User::create($data);
        }
        else
        {
            $data['updated_at'] = $this->time;
            $user->update($data);
        }

        $miniProgram   = EasyWeChat::miniProgram(); // 小程序
        $decryptedData = $miniProgram->encryptor->decryptData($session_key_row->session_key, $iv, $encryptedData);

        if(!empty($decryptedData['unionId']))
        {
            $user->update(['unionid'=>$decryptedData['unionId']]);
        }
        //dd($decryptedData);

        $result = [
            'user_id'     => $user->id,
            'is_new_user' => $is_new_user,
        ];
        return $this->ok($result);
    }
}
